package com.xframe.xdal.core.util;

import com.xframe.xdal.core.domain.IDynamicModel;
import com.xframe.xdal.core.model.mapping.ITableInfo;
import com.xframe.xdal.core.model.mapping.TableInfoBuilder;

/**
 * 模型帮助类
 *
 * @author xufeng
 */
public class ModelUtil {

    /**
     * 通过ITableInfo, 拷贝模型
     *
     */
    public static <T> T cloneByTableInfo(T model, ITableInfo tableInfo){
        try {
            T cloneObject = (T) model.getClass().newInstance();
            tableInfo.getColumnMappingList().forEach(columnMapping -> {
                try {
                    XReflect.setFieldValue(cloneObject, columnMapping.getFieldName(), XReflect.getFieldValue(model, columnMapping.getFieldName()));
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            });
            return cloneObject;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 通过ITableInfo, 拷贝模型
     *
     */
    public static Object cloneByTableInfo(Object model,Class<?> dataType, ITableInfo tableInfo){
        try {
            Object cloneObject = dataType.newInstance();
            tableInfo.getColumnMappingList().forEach(columnMapping -> {
                try {
                    XReflect.setFieldValue(cloneObject, columnMapping.getFieldName(), XReflect.getFieldValue(model, columnMapping.getFieldName()));
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            });
            return cloneObject;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }



    public static <T> T cloneByTableInfo(T model){
        return cloneByTableInfo(model, TableInfoBuilder.BuildTableInfoByAnnotation(model.getClass()));
    }
    /**
     * 是否动态对象
     *
     */
    public static boolean isDynamicModel(Class<?> dataType){
        if(IDynamicModel.class.isAssignableFrom(dataType)){
            return true;
        }
        return false;
    }

    /**
     * 是否动态对象
     *
     */
    public static boolean isDynamicModel(Object bean){
        return isDynamicModel(bean.getClass());
    }
}
